package com.suzus.aiService.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileNameUtil;
import com.suzus.aiService.common.result.Result;
import com.suzus.aiService.common.utils.AuthAccess;
import com.suzus.aiService.pojo.entity.Case;
import com.suzus.aiService.pojo.entity.HospitalDesc;
import com.suzus.aiService.pojo.entity.Medicine;
import com.suzus.aiService.pojo.vo.CaseVO;
import com.suzus.aiService.pojo.vo.MedicineVO;
import com.suzus.aiService.service.AskService;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@CrossOrigin
@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {
    @Autowired
    AskService askService;
    private static final String ROOT_PATH = System.getProperty("user.dir") + File.separator + "files";

    private String saveFile(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        //aa.png
        String mainName = FileNameUtil.mainName(originalFilename);
        String extName = FileUtil.extName(originalFilename);
        if (!FileUtil.exist(ROOT_PATH)) {
            FileUtil.mkdir(ROOT_PATH);//不存在创建
        }
        if (FileUtil.exist(ROOT_PATH + File.separator + originalFilename)) {
            originalFilename = System.currentTimeMillis() + "_" + mainName + "." + extName;//存在命名
            System.out.println(originalFilename+"被创建");
        }
        File saveFile = new File(ROOT_PATH + File.separator + originalFilename);
        file.transferTo(saveFile);//存储本地
        System.out.println("存储成功");
        return "http://localhost:8088/file/download/" + originalFilename;
    }

    //此接口为通过图片上传获取药品名称和药品信息
    //此接口仅用于药品识别
    @PostMapping("/uploadForMedicine")
    public Result<MedicineVO> uploadForMedicine(MultipartFile file) throws Exception {
        Medicine medicine = askService.getMedicineByPicture(file.getBytes());
        String url=null;
        try{
            url = saveFile(file);
        } catch (IOException e) {
            return Result.error("Upload failed");
        }
        return Result.success(MedicineVO.builder().
                url(url).
                name(medicine.getName()).
                intro(medicine.getIntro()).
                build());
    }
    //此接口仅用于病历单识别到症状
    @PostMapping("/uploadForSheet")
    public Result<CaseVO> uploadForSheet(MultipartFile file) throws Exception {
        Case caseAnalysis=askService.getSymptomBySheet(file.getBytes());

        String url=null;
        try{
            url = saveFile(file);
        } catch (IOException e) {
            return Result.error("Upload failed");
        }

        return Result.success(CaseVO.builder().desc(caseAnalysis.getDesc()).url(url).build());
    }
    //此接口仅用于病历单识别到医院
    @PostMapping("/uploadForHospital")
    public Result<CaseVO> uploadForHospital(MultipartFile file) throws Exception {
        HospitalDesc caseAnalysis=askService.getHospitalByPicture(file.getBytes());
        String url=null;
        try{
            url = saveFile(file);
        } catch (IOException e) {
            return Result.error("Upload failed");
        }
        return Result.success(CaseVO.builder().desc(caseAnalysis.getDesc()).url(url).build());
    }

    @AuthAccess
    @GetMapping("/download/{fileName}")
    public Result download(@PathVariable String fileName, HttpServletResponse response) throws IOException {
        System.out.println("进入download逻辑");
        String filePath = ROOT_PATH + File.separator + fileName;
        System.out.println(filePath);
        if (!FileUtil.exist(filePath)) {
            return Result.error("无法访问");
        }
        byte[] bytes = FileUtil.readBytes(filePath);
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes);
        outputStream.flush();
        outputStream.close();
        return  Result.success();
    }
}
